<?php
class AuthController extends Zend_Controller_Action {

    public function init(){

        $this->initView();
        $this->view->baseUrl = $this->_request->getBaseUrl();
    }

    public function indexAction(){

        $this->_redirect('/index');
    }

    public function loginAction(){

        $this->view->title = 'Log In';
        $this->view->messages = array();
        if($this->_request->isPost()){

            Zend_Loader::loadClass('PostFilter');
            $filter = new PostFilter();
            $filter->filter();
            if($this->_request->getPost('name') == ''){

                $this->view->messages += (array)'Username cannot be empty.';

            }else{
                
                Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
                $db = Zend_Registry::get('db');
                $authAdapter = new Zend_Auth_Adapter_DbTable($db);
                $authAdapter->setTableName('user')
                            ->setIdentityColumn('name')
                            ->setCredentialColumn('pass');
                
                $authAdapter->setIdentity($this->_request->getPost('name'))
                            ->setCredential($this->_request->getPost('pass'));
                
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                if($result->isValid()){
                    
                    $data = $authAdapter->getResultRowObject(null,'pass');
                    $auth->getStorage()->write($data);
                    $this->_redirect('/album/index');
                }else{
                    
                    $this->view->messages += (array)'Invalid username or password.';
                }
                


            }
        }
    }
    
    public function logoutAction(){
        
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
    }
}
    
